package com.sz.mes.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sz.mes.entity.InstockLattice;
import com.sz.mes.entity.warehouse.InstockRecord;
import com.sz.mes.mapper.InstockLatticeMapper;
import com.sz.mes.mapper.warehouse.InstockRecordMapper;
import com.sz.mes.vo.ShelfIdAndGoodQuantityVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.diboot.core.vo.*;
import com.diboot.iam.annotation.OperationCons;
import com.diboot.iam.annotation.BindPermission;
import com.diboot.iam.annotation.Log;
import com.sz.mes.entity.Instock;
import com.sz.mes.dto.InstockDTO;
import com.sz.mes.vo.InstockListVO;
import com.sz.mes.vo.InstockDetailVO;
import com.sz.mes.service.InstockService;
import com.sz.mes.controller.BaseCustomCrudRestController;
import lombok.extern.slf4j.Slf4j;
import javax.validation.Valid;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 入库 相关Controller
 *
 * @author hem
 * @version 1.0
 * @date 2023-05-25
 * Copyright © szhs
 */
@RestController
@RequestMapping("/instock")
@BindPermission(name = "入库")
@Slf4j
public class InstockController extends BaseCustomCrudRestController<Instock> {

    @Autowired
    private InstockService instockService;

    @Autowired
    private InstockLatticeMapper instockLatticeMapper;

    @Autowired
    private InstockRecordMapper instockRecordMapper;

    /**
     * 查询ViewObject的分页数据
     * <p>
     * url请求参数示例: /list?field=abc&pageIndex=1&orderBy=abc:DESC
     * </p>
     *
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_LIST)
    // @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping("/list")
    public JsonResult getViewObjectListMapping(InstockDTO queryDto, Pagination pagination) throws Exception {
        QueryWrapper<Instock> instockQueryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(queryDto.getAcceptanceNum())) {
            instockQueryWrapper.like("acceptance_num", queryDto.getAcceptanceNum());
        } else if (!StringUtils.isEmpty(queryDto.getGoodsName())) {
            instockQueryWrapper.like("goods_name", queryDto.getGoodsName());
        } else if (!StringUtils.isEmpty(queryDto.getGoodsCode())) {
            instockQueryWrapper.like("goods_code", queryDto.getGoodsCode());
        } else if (!StringUtils.isEmpty(queryDto.getSpecifications())) {
            instockQueryWrapper.like("specifications", queryDto.getSpecifications());
        } else {
            return super.getViewObjectList(queryDto, pagination, InstockListVO.class);
        }
        return super.getEntityListWithPaging(instockQueryWrapper, pagination);
    }

    /**
     * 根据入库单号查询入库详情
     *
     * @param acceptanceNum
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    // @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/{acceptanceNum}")
    public JsonResult detail(@PathVariable("acceptanceNum") String acceptanceNum) throws Exception {
        return instockService.getDetail(acceptanceNum);
    }

    /**
     * 编辑入库
     *
     * @param entity
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_UPDATE)
    // @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/update")
    public JsonResult updateByAcceptanceNum(@Valid @RequestBody InstockDTO entity) throws Exception {
        return instockService.updateInstock(entity);
//        return super.updateEntity(id, entity);
    }

    /**
     * 根据id删除资源对象
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DELETE)
    // @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @DeleteMapping("/{id}")
    public JsonResult deleteEntityMapping(@PathVariable("id") Long id) throws Exception {
        return super.deleteEntity(id);
    }

    /**
     * 获取入库单号
     *
     * @return
     */
    @GetMapping("/getNumber")
    public JsonResult getNumber() {
        long time = System.currentTimeMillis();
        return JsonResult.OK("RK" + time);
    }

    /**
     * 入库
     *
     * @param entity
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_CREATE)
    // @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/insert")
    public JsonResult insert(@Valid @RequestBody InstockDTO entity) throws Exception {
//        Set<Long> shelfIdSet = new HashSet<>();
//        for (ShelfIdAndGoodQuantityVO shelfIdAndGoodQuantityVO : entity.getShelfIdAndGoodsQuantityVOList()) {
//            if (shelfIdSet.contains(shelfIdAndGoodQuantityVO.getLatticeId())) {
//                return JsonResult.FAIL_OPERATION("库位重复");
//            } else {
//                shelfIdSet.add(shelfIdAndGoodQuantityVO.getLatticeId());
//            }
//        }
        JsonResult jsonResult = null;
        try {
            jsonResult = instockService.insertInstock(entity);
            if (jsonResult.getMsg().equals("操作成功")) {
                return jsonResult;
            }
        } catch (Exception e) {
            // 入库表删除记录
            instockService.deleteEntity(entity.getId());
            // 入库货格表删除记录
            QueryWrapper<InstockLattice> instockLatticeQueryWrapper = new QueryWrapper<>();
            instockLatticeQueryWrapper.eq("instock_id", entity.getId());
            instockLatticeMapper.delete(instockLatticeQueryWrapper);
            // 入库记录表删除记录
            QueryWrapper<InstockRecord> instockRecordQueryWrapper = new QueryWrapper<>();
            instockRecordQueryWrapper.eq("instock_id", entity.getId());
            instockRecordMapper.delete(instockRecordQueryWrapper);
            return JsonResult.FAIL_EXCEPTION("入库失败");
        } finally {
            return jsonResult;
        }
        // String msg = jsonResult.getMsg();
        // if (msg.equals("操作成功")) {
        // return jsonResult;
        // } else {
        // //入库表删除记录
        // instockService.deleteEntity(entity.getId());
        // //入库货格表删除记录
        // QueryWrapper<InstockLattice> instockLatticeQueryWrapper = new QueryWrapper<>();
        // instockLatticeQueryWrapper.eq("instock_id", entity.getId());
        // instockLatticeMapper.delete(instockLatticeQueryWrapper);
        // //入库记录表删除记录
        // QueryWrapper<InstockRecord> instockRecordQueryWrapper = new QueryWrapper<>();
        // instockRecordQueryWrapper.eq("instock_id", entity.getId());
        // instockRecordMapper.delete(instockRecordQueryWrapper);
        // return JsonResult.OK("入库失败");
        // }
    }

    /**
     * 撤销入库
     *
     * @param entity
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_CREATE)
    // @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/unInsert")
    public JsonResult unInsert(@Valid @RequestBody Instock entity) throws Exception {
        return instockService.unInsert(entity);
    }


    /**
     * 根据单据编号查询入库数量之和
     *
     * @param receiptNum
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    // @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/getTotalQuantity/{receiptNum}")
    public JsonResult getTotalQuantity(@PathVariable("receiptNum") String receiptNum) throws Exception {
        return instockService.getTotalQuantity(receiptNum);
    }
}
